package java实验五;
import java.util.Scanner;

public class 程序六 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("请输入四则运算表达式，或输入'exit'退出：");
            String input = scanner.nextLine();

            if ("exit".equalsIgnoreCase(input)) {
                System.out.println("程序已退出。");
                break;
            }

            try {
                // 尝试解析并计算
                double result = calculate(input);
                
                // 如果输入包含'='，则进一步验证用户提供的结果
                if (input.contains("=")) {
                    String[] parts = input.split("=");
                    double expected = Double.parseDouble(parts[1].trim());
                    if (Math.abs(result - expected) < 0.0001) { // 小误差容限
                        System.out.println("计算结果与预期相符！");
                    } else {
                        System.out.printf("计算结果不匹配！正确结果为: %.4f, 但您输入的是: %.4f%n", result, expected);
                    }
                } else {
                    System.out.printf("结果为: %.4f%n", result);
                }
            } catch (NumberFormatException | ArithmeticException e) {
                System.out.println("输入格式错误或运算错误，请确保输入正确的四则运算表达式。");
            }
        }

        scanner.close();
    }

    private static double calculate(String expression) throws NumberFormatException, ArithmeticException {
        String[] parts = expression.split("[+\\-*/]");
        double num1 = Double.parseDouble(parts[0]);
        double num2 = Double.parseDouble(parts[1]);
        char operator = expression.charAt(parts[0].length());

        switch (operator) {
            case '+':
                return num1 + num2;
            case '-':
                return num1 - num2;
            case '*':
                return num1 * num2;
            case '/':
                if (num2 == 0) throw new ArithmeticException("除数不能为0");
                return num1 / num2;
            default:
                throw new IllegalArgumentException("不支持的运算符");
        }
    }
}
